﻿using Microsoft.IdentityModel.Tokens;
using S2_1.Models;
using S2_1.Services;
using S2_1.Services.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Web.Http;
using System.Web.UI.WebControls;

namespace S2_1.Controllers
{
    public class IdentityController : ApiController
    {
        //老版本，依赖注入，官方不支持，需要用三方插件才能支持
        [HttpGet]
        [Route("api/security-question")]
        public List<string> GetSecurityQuestion()
        {
            return new List<string>
            {
                "安全问题1",
                "安全问题2",
                "安全问题3"
            };
        }

        [HttpPost]
        [Route("api/register")]
        public AppResult Register(User user)
        {
            using (var service = new UserService())
            {
                var products = service.Add(user);
            }
            return new AppResult();
        }
        [HttpPost]
        [Route("api/login")]
        public AppResult<string> Login(string email, string password)
        {
            using (var service = new UserService())
            {
                var user = service.GetUserByEmailAndPassword(email, password);
                if (user == null) return new AppResult<string>(false, "用户名或密码不正确");

                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes("your-secret-key");
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                            new Claim(ClaimTypes.Name, user.Id.ToString()),
                    }),
                    Expires = DateTime.UtcNow.AddHours(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return new AppResult<string>(tokenString);
            }
        }
        [HttpPost]
        [Route("api/forgot-password")]
        public AppResult<string> ForgotPassword(string email)
        {
            using (var service = new UserService())
            {
                var safeQuestion = service.GetSafeQuestion(email);
                return new AppResult<string>(safeQuestion);
            }
        }

        [HttpPost]
        [Route("api/reset-password")]
        public AppResult ResetPassword(ResetPasswordInput input)
        {
            using (var service = new UserService())
            {
                var safeQuestion = service.RestPassword(input);
                return new AppResult();
            }
        }
    }
}
